using System;
using System.Collections.Generic;
using System.Text;
using BSDS.Core.Data.Remote.Account;
using BSDS.Core.Model.Services;

namespace BSDS.Commands.Commands.Implementation
{
    public class ListCommand : CommandBase
    {
        private readonly bool showDetails;
        private readonly string dataSourceName;

        private readonly AccountService accountService;

        public ListCommand(AccountService accountService, bool showDetails, string dataSourceName)
        {
            this.accountService = accountService;
            this.showDetails = showDetails;
            this.dataSourceName = dataSourceName;
        }

        public override CommandResult Execute(ExecutionContext context)
        {
            if(showDetails)
            {
                var dataSourceInfo = accountService.GetDataSourceInformation(dataSourceName);

                Console.WriteLine(FormatDetailInfo(dataSourceInfo));
            }
            else
            {
                var dataSourceInfos = accountService.GetAccountGeneralInforamtion();

                Console.WriteLine(FormatGeneralInfo(dataSourceInfos));
            }

            return CommandResult.Success();
        }

        private static string FormatDetailInfo(DataSourceInfo dataSourceInfo)
        {
            return "Name: " + dataSourceInfo.Name + Environment.NewLine +
                   "Entity type name: " + dataSourceInfo.EntityTypeName + Environment.NewLine +
                   "AccessId: " + dataSourceInfo.AccessId + Environment.NewLine +
                   "Query URL: " + dataSourceInfo.Href + Environment.NewLine +
                   "Last update: " + dataSourceInfo.LastUpdate;
        }

        private static string FormatGeneralInfo(IEnumerable<DataSourceInfo> dataSourceInfos)
        {
            var resultBuilder = new StringBuilder();
            resultBuilder.Append("Available datasources: ");

            foreach (var dataSourceInfo in dataSourceInfos)
            {
                resultBuilder.Append(Environment.NewLine).Append(dataSourceInfo.Name);
            }

            return resultBuilder.ToString();
        }
    }
}